import requests
import json

class WeChatWorkSender:
    def __init__(self, corp_id, app_secret, agent_id):
        self.corp_id = corp_id
        self.app_secret = app_secret
        self.agent_id = agent_id
        self.access_token = self.get_access_token()

    def get_access_token(self):
        """获取访问令牌"""
        url = f"https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={self.corp_id}&corpsecret={self.app_secret}"
        response = requests.get(url)
        result = json.loads(response.text)
        if result.get("errcode") == 0:
            return result["access_token"]
        else:
            raise Exception(f"获取access_token失败: {result}")

    def send_text_message(self, user_id, content):
        """发送文本消息给指定用户"""
        if not self.access_token:
            self.access_token = self.get_access_token()
            
        url = f"https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={self.access_token}"
        data = {
            "touser": user_id,  # 接收消息的用户ID
            "msgtype": "text",
            "agentid": self.agent_id,
            "text": {"content": content},
            "safe": 0
        }
        
        response = requests.post(url, data=json.dumps(data))
        result = json.loads(response.text)
        
        if result.get("errcode") == 0:
            print("消息发送成功")
            return True
        else:
            print(f"消息发送失败: {result}")
            return False

if __name__ == "__main__":
    # 替换为你的企业微信信息
    CORP_ID = "wwfcadb648653e02c7"  # 在企业微信管理后台获取
    APP_SECRET = "awTruiNAr-V9_9g8JXYaUIHuZU8MiMbEUrGPioiA93Y"  # 在创建的应用中获取
    AGENT_ID = 1000002  # 应用的AgentID
    
    # 初始化发送器
    sender = WeChatWorkSender(CORP_ID, APP_SECRET, AGENT_ID)
    
    # 发送消息（接收用户的userid，文本内容）
    sender.send_text_message("娄安", "这是通过企业微信API发送的消息")
